//! 路由守卫
import router from './router'
import store from './store'
import NProgress from 'nprogress' // 引入一份进度条插件
import 'nprogress/nprogress.css' // 引入进度条样式

// 定义白名单
const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  const token = store.getters.token // token必须要写在路由守卫里面
  if (token) {
    if (to.path === '/login') {
      next('/')
      NProgress.done() // 重定向必须要加结束
    } else {
      //! 调用获取用户资料
      const userInfo = store.state.user.userInfo.id
      if (!userInfo) {
        // 1.没有用户资料就获取一下
        await store.dispatch('user/getUserProfile')
        // 2.调用权限处理方法整理动态路由
        // const userAsyncRoutes = await store.dispatch('permission/filterRoutes', menuList)
        // 3. 通过router.addRoutes()添加到路由示例中
        // { path: '*', redirect: '/404', hidden: true }
        // router.addRoutes([...userAsyncRoutes, { path: '*', redirect: '/404', hidden: true }])

        // next(to.path)
      }
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach((to, from) => {
  NProgress.done()
})
